<?php
/**
 * Created by PhpStorm.
 * User: TheLuther
 * Date: 2019/11/10
 * Time: 21:14
 */
namespace app\common\model;

use think\Exception;
use think\Model;
use think\Db;
use think\Config;

class FormField extends model{
    public $type = array();
    public $createsql = array();
    public $pattern = array();

    public $systemfield = array('url','title','uid','addtime','edittime','uname','clientip','status','guid');

    protected static $instance;
    public static function instance($options = [])
    {
        if (is_null(self::$instance)) {
            self::$instance = new self($options);
        }
        return self::$instance;
    }

    protected function initialize()
    {
        $this->type[''] = '';
        $this->type['textbox'] = '单行文本';
        $this->type['textarea'] = '多行文本';
        $this->type['radio'] = '单选';
        $this->type['checkbox'] = '多选';
        $this->type['select'] = '下拉';
        $this->type['combotree'] = '下拉树';
        $this->type['image'] = '图片';
        $this->type['file'] = '文件';
        $this->type['date'] = '日期';
        $this->type['ueditor'] = '百度编辑器';

        $this->pattern[''] = array('rule'=>'','errortip'=>'');
        $this->pattern['数字'] = array("rule"=>"/^[0-9.-]+$/");
        $this->pattern['正整数'] = array("rule"=>"/^[0-9-]+$/");
        $this->pattern['字母数字'] = array("rule"=>"/^[a-xA-Z0-9]+$/");
        $this->pattern['电子信箱'] = array("rule"=>"/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/");
        $this->pattern['时间日期'] = array("rule"=>"/^[0-9:\s-]+$/");

        $this->createsql[''] = '';
        $this->createsql['字符串(255个字符)'] = "char(255) not null default ''";
        $this->createsql['整数(3位)'] = "int(3) not null default '0'";
        $this->createsql['整数(10位)'] ="int(10) not null default '0'";
        $this->createsql["长文本"] = "text not null";
        $this->createsql["特长文本"] = "mediumtext not null";

        parent::initialize(); // TODO: Change the autogenerated stub
    }

    public function add($data){
        try{
            if(in_array($data['name'],$this->systemfield)){
                return '该字段为系统保留字段，操作失败';
            }
            //如果有创建字段sql语句，则对表结构进行处理
            //如果创建字段sql为空，则只记录字段信息，不对表结构进行处理
            if($data['sql']){
                $formid = $data['formid'];
                $form = Db::name('form')->where(['guid'=>$formid])->findOrEmpty();
                $ismain = $data['ismain'];

                if(!$ismain && empty($form['extratable'])){
                    return '附表不存在，只能选择主表';
                }
                else{
                    $tablename = config('database.prefix').($ismain?$form['maintable']:$form['extratable']);
                    $sql = "alter table ".$tablename." add column `".$data['name']."` ".$data['sql'].";";
                    Db::execute($sql);
                }
            }
            Db::name('form_field')->insert($data);
            return true;
        }
        catch(Exception $ex){
            return $ex->getMessage();
        }
    }

    public function edit($data){
        try{
            $field = Db::name('form_field')->where(['guid'=>$data['guid']])->findOrEmpty();
            $formid = $data['formid'];
            $form = Db::name('form')->where(['guid'=>$formid])->findOrEmpty();
            $ismain = $data['ismain'];
            $prefix = config('database.prefix');
            $newtablename = $prefix. ($ismain?$form['maintable']:$form['extratable']);

            $ischange = ($data['ismain']!=$field['ismain']) || ($data['sql']!=$field['sql']) || ( $data['name']!=$field['name'] );
            if($ischange){
                //没有换主从表
                if($ismain == $field['ismain']){
                    if( $data['sql'] != $field['sql'] )
                    {
                        if(empty($field['sql'])){
                            $sql = "alter table ".$newtablename." add column `".$data['name']."` ".$data['sql'].";";
                            DB::execute($sql);
                        }else if(empty($data['sql']))
                        {
                            $sql = "alter table `".$newtablename."` drop column `".$field['name']."`";
                            DB::execute($sql);
                        }
                        else{
                            $sql = "alter table `".$newtablename."` change `".$field['name']."` `".$data['name']."` ".$data['sql'];
                            Db::execute($sql);
                        }
                    }
                }else{
                    //换主从表则将字段从旧表删除，在新表创建
                    $oldtablename = $prefix.($field['ismain']?$form['maintable']:$form['extratable']);
                    $sql = "alter table `".$oldtablename."` drop column `".$field['name']."`";
                    DB::execute($sql);
                    if($data['sql']){
                        $sql = "alter table ".$newtablename." add column `".$data['name']."` ".$data['sql'].";";
                        DB::execute($sql);
                    }
                }
            }
            Db::name('form_field')->where(['guid'=>$data['guid']])->update($data);
            return true;
        }
        catch(Exception $ex){
            return $ex->getMessage();
        }
    }

    public function remove($where){
        $model = Db::name('form_field')->where($where)->findOrEmpty();
        if(!$model)
        {
            return '参数错误';
        }
        try{
            if($model['sql']){
                $form = Db::name('form')->where(['guid'=>$model['formid']])->findOrEmpty();
                $ismain = $model['ismain'];
                $prefix = config('database.prefix');
                $tablename = $prefix. ($ismain?$form['maintable']:$form['extratable']);
                $sql = "alter table `".$tablename."` drop column `".$model['name']."`";
                DB::execute($sql);
            }
            Db::name('form_field')->where($where)->delete();
        }
        catch (Exception $ex){
            return $ex->getMessage();
        }
        return true;
    }

    public function getFields($formid){
        $list = Db::name('form_field')->where(['formid'=>$formid])->order('sort desc,edittime desc')->select();
        $newlist = array();
        foreach($list as $v){
            $newlist[$v['name']] = $v;
        }
        return $newlist;
    }

}